import React, { useEffect, useRef, useState } from 'react';
import './index.css';
import { connect } from 'react-redux';
import { ctrlSong, openSongPage } from '../../../store/actions/music.action';
import { configPlayBtn } from '../../../utils/progressbar';
import { generateArtists, once } from '../../../utils/common';

const mapStateToProps = state => {
    return {
        music: state.music
    }
}
const mapDispatchToProps = dispatch => {
    return {
        ctrlSong: (...args) => dispatch(ctrlSong(...args)),
        openSongPage: (...args) => dispatch(openSongPage(...args)),
    }
}
const configPlayBtnOnce = once(configPlayBtn),
    playBtnClassNames = {
        prefix: 'iconfont icon-play',
        play: 'icon-bofang2',
        pause: 'icon-zanting6'
    },
    parentName = 'AudioPlay';

const AudioPlay = ({ music, ctrlSong, openSongPage }) => {
    const playBtnRef = useRef();
    useEffect(() => {
        if (music.curSong && music.curSong.url) {
            console.log("audio player init");
            let curAudio = music.curSong.audio,
                playBtn = playBtnRef.current;
            configPlayBtnOnce(curAudio, playBtn, playBtnClassNames, ctrlSong, parentName);
            playBtn.className = `${playBtnClassNames.prefix} ${music.isPlaying ? playBtnClassNames.pause : playBtnClassNames.play}`;
        }
    }, [music.curSong.url, music.isPlaying]);
    return (
        <div className={`audio-area ${music.curSong.url ? 'show' : ''}`} onClick={() => openSongPage()}>
            <div className="music-disc"></div>
            <div className="music-detail">
                {music.curSong && music.curSong.name ? `${music.curSong.name} - ${generateArtists(music.curSong.artists)}` : ''}
            </div>
            <span className="iconfont " ref={playBtnRef}></span>
            <span className="iconfont icon-liebiao"></span>
        </div>
    );
}

export default connect(mapStateToProps, mapDispatchToProps)(AudioPlay);
